/**
 * Markdown PDF 查看器组件
 * 
 * 使用方式（在 Markdown 中）：
 * ```pdf
 * https://example.com/document.pdf
 * ```
 * 
 * 或内嵌 PDF：
 * ![PDF文档](document.pdf)
 */

import React, { useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import { Button } from '@/components/ui/button';
import { ChevronLeft, ChevronRight, ZoomIn, ZoomOut, Download, Maximize2 } from 'lucide-react';

// 配置 PDF.js worker（使用本地文件，不从 CDN 加载）
// pdfjs-dist 包中已包含 worker 文件
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.min.mjs',
    import.meta.url
).toString();

// 导入 react-pdf 样式
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';

/**
 * PDF 查看器组件
 * @param {Object} props
 * @param {string} props.url - PDF 文件 URL
 */
export const MarkdownPdfViewer = ({ url = '' }) => {
    const [numPages, setNumPages] = useState(null);
    const [pageNumber, setPageNumber] = useState(1);
    const [scale, setScale] = useState(1.0);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    // PDF 加载成功
    const onDocumentLoadSuccess = ({ numPages }) => {
        setNumPages(numPages);
        setLoading(false);
        setError(null);
    };

    // PDF 加载失败
    const onDocumentLoadError = (error) => {
        console.error('PDF 加载失败:', error);
        setError('PDF 文件加载失败，请检查文件路径或网络连接');
        setLoading(false);
    };

    // 上一页
    const goToPrevPage = () => {
        setPageNumber(prev => Math.max(1, prev - 1));
    };

    // 下一页
    const goToNextPage = () => {
        setPageNumber(prev => Math.min(numPages, prev + 1));
    };

    // 放大
    const zoomIn = () => {
        setScale(prev => Math.min(3.0, prev + 0.2));
    };

    // 缩小
    const zoomOut = () => {
        setScale(prev => Math.max(0.5, prev - 0.2));
    };

    // 下载 PDF
    const downloadPdf = () => {
        const link = document.createElement('a');
        link.href = url;
        link.download = url.split('/').pop() || 'document.pdf';
        link.click();
    };

    // 全屏查看
    const openFullscreen = () => {
        window.open(url, '_blank');
    };

    if (!url) {
        return (
            <div className="my-6 p-8 border border-gray-200 dark:border-gray-700 rounded-lg bg-gray-50 dark:bg-gray-800 text-center">
                <p className="text-gray-500 dark:text-gray-400">
                    ❌ 未提供 PDF 文件路径
                </p>
            </div>
        );
    }

    return (
        <div className="my-6 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden not-prose">
            {/* 工具栏 */}
            <div className="bg-gray-50 dark:bg-gray-800 px-4 py-3 border-b border-gray-200 dark:border-gray-700">
                <div className="flex items-center justify-between">
                    {/* 左侧：页码控制 */}
                    <div className="flex items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={goToPrevPage}
                            disabled={pageNumber <= 1 || loading}
                        >
                            <ChevronLeft className="size-4" />
                        </Button>

                        <span className="text-sm text-gray-700 dark:text-gray-300 px-2">
                            {loading ? '加载中...' : `${pageNumber} / ${numPages || '?'}`}
                        </span>

                        <Button
                            variant="outline"
                            size="sm"
                            onClick={goToNextPage}
                            disabled={pageNumber >= numPages || loading}
                        >
                            <ChevronRight className="size-4" />
                        </Button>
                    </div>

                    {/* 中间：缩放控制 */}
                    <div className="flex items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={zoomOut}
                            disabled={scale <= 0.5 || loading}
                            title="缩小"
                        >
                            <ZoomOut className="size-4" />
                        </Button>

                        <span className="text-sm text-gray-700 dark:text-gray-300 px-2 min-w-[60px] text-center">
                            {Math.round(scale * 100)}%
                        </span>

                        <Button
                            variant="outline"
                            size="sm"
                            onClick={zoomIn}
                            disabled={scale >= 3.0 || loading}
                            title="放大"
                        >
                            <ZoomIn className="size-4" />
                        </Button>
                    </div>

                    {/* 右侧：操作按钮 */}
                    <div className="flex items-center gap-2">
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={downloadPdf}
                            disabled={loading}
                            title="下载 PDF"
                        >
                            <Download className="size-4" />
                        </Button>

                        <Button
                            variant="outline"
                            size="sm"
                            onClick={openFullscreen}
                            disabled={loading}
                            title="新窗口打开"
                        >
                            <Maximize2 className="size-4" />
                        </Button>
                    </div>
                </div>
            </div>

            {/* PDF 内容 */}
            <div className="bg-gray-100 dark:bg-gray-900 p-4 flex justify-center">
                {error ? (
                    <div className="p-8 text-center">
                        <p className="text-red-500 dark:text-red-400">{error}</p>
                    </div>
                ) : (
                    <div className="shadow-lg">
                        <Document
                            file={url}
                            onLoadSuccess={onDocumentLoadSuccess}
                            onLoadError={onDocumentLoadError}
                            loading={
                                <div className="p-8 text-center">
                                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
                                    <p className="text-gray-500 dark:text-gray-400">加载 PDF...</p>
                                </div>
                            }
                        >
                            <Page
                                pageNumber={pageNumber}
                                scale={scale}
                                className="bg-white"
                                renderTextLayer={true}
                                renderAnnotationLayer={true}
                            />
                        </Document>
                    </div>
                )}
            </div>

            {/* 底部信息栏 */}
            <div className="bg-gray-50 dark:bg-gray-800 px-4 py-2 border-t border-gray-200 dark:border-gray-700">
                <p className="text-xs text-gray-500 dark:text-gray-400 text-center">
                    💡 提示：使用工具栏按钮翻页、缩放，或点击新窗口打开完整查看
                </p>
            </div>
        </div>
    );
};

// 设置 displayName 帮助父组件识别
MarkdownPdfViewer.displayName = 'MarkdownPdfViewer';

export default MarkdownPdfViewer;

